package com.xjh.basestudy.javabase.thread_final.threadpool.demo;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Author:XuJianHua
 * @Date:2022/10/28
 * @Description: 全民公社项目中的线程池工具类
 *
 * 全民公社中使用线程池实现的功能：
 *
 */
@Component
public class ThreadPoolUtils {

  private static final Logger logger = LoggerFactory.getLogger(ThreadPoolUtils.class);
  private static final ExecutorService threadPool;

  static {
    logger.info("线程池初始化开始......");
    // 返回可用处理器的Java虚拟机的数量
    int corePoolSize = Runtime.getRuntime().availableProcessors();
    logger.info("线程池初始化开始，核心线程数：{}", corePoolSize);
    int maxPoolSize = Runtime.getRuntime().availableProcessors() * 2;
    logger.info("线程池初始化开始，最大线程数：{}", maxPoolSize);
    // 创建一个线程工厂
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("ThreadPoolUtils").build();

    threadPool = new ThreadPoolExecutor(
        corePoolSize,
        maxPoolSize,
        // 空闲线程存活时间
        60,
        // 存活时间的单位
        TimeUnit.SECONDS,
        // 任务队列
        new LinkedBlockingDeque<>(20),
        // 用于创建线程的工厂类（可选参数）
        threadFactory,
        // 拒绝策略（可选参数）
        new ThreadPoolExecutor.AbortPolicy()

    );
    logger.info("线程池初始化完成！");
  }
// 使用线程池工具类需要调用的方法，参数是任意一个方法，调用了这个东西会起什么作用呢？
  // 当方法在线程池内执行，
  public static void execute(Runnable runnable) {
    threadPool.execute(runnable);
  }

  public static Future<?> submit(Runnable runnable) {
    return threadPool.submit(runnable);
  }

  public static Future<?> submit(Callable<?> callable) {
    return threadPool.submit(callable);
  }

  public static ExecutorService getThreadPool() {
    return threadPool;
  }


}
